package com.jing.weibo.controller.info;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import weibo4j.model.Status;
import weibo4j.model.WeiboException;

import com.jing.system.comm.BaseController;
import com.jing.system.comm.contants.SystemCons;
import com.jing.system.comm.contants.WeiboCons;
import com.jing.system.utils.StringUtil;
import com.jing.system.utils.matche.MatcheUtil;
import com.jing.weibo.pojo.info.Info;
import com.jing.weibo.pojo.info.InfoType;
import com.jing.weibo.pojo.user.UserInfo;
import com.jing.weibo.service.info.InfoService;
import com.jing.weibo.service.info.InfoTypeService;
import com.jing.weibo.ws.sina.TimelineService;

/**
 * 信息的Controller
 * @author jing.yue
 * @version 2012/09/21 1.0.0
 */
@Controller
public class InfoController extends BaseController {

	private static final Logger logger = Logger.getLogger(InfoController.class);

	@Autowired
	private TimelineService timelineService;
	@Autowired
	private InfoService infoService;
	@Autowired
	private InfoTypeService infoTypeService;

	/**
	 * 添加信息
	 * @return
	 */
	@RequestMapping(value = "/info/json/addInfo")
	@ResponseBody
	public ModelMap addInfo(HttpServletRequest request, Info info) {
		String result = null;
		ModelMap modelMap = new ModelMap();
		StringBuffer errorWeiboMsg = new StringBuffer();
		UserInfo userInfo = getSessionUser(request);
		//不为管理员
		if(userInfo.getIsadmin().intValue() != 1) {
			logger.error(userInfo.getNickname() + ": 您不是管理员!");
			result = ERROR_NOT_ADMIN;
		}
		else {
			try {

				//处理是否有相似内容
				List<Info> resembleList = new ArrayList<Info>();
				List<Info> infos = infoService.findAllInfo();
				for (Info i : infos) {
					if(MatcheUtil.matcheSim(info.getContent().trim(), i.getContent()) > SystemCons.CONTENT_RESEMBLE_NUM) {
						resembleList.add(i);
						break;
					}
				}
				//存在相似内容
				if(resembleList.size() > 0) {
					result = "error_resemble";
					modelMap.put("resembleList", resembleList);
				}
				else {
					Status status = null;
					if(StringUtil.isNotEmpty(info.getImg())) {
						StringBuffer imgUrl = new StringBuffer(SystemCons.ABSOLUTE_PATH);
						imgUrl.append(File.separator).append(SystemCons.UPLOAD_IMAGE_PATH).append(info.getImg());
						//发送到微博
						status = timelineService.updateStatus(info.getContent().trim(), imgUrl.toString(), userInfo.getToken());
					}
					else {
						//发送到微博
						status = timelineService.updateStatus(info.getContent().trim(), userInfo.getToken());
					}
					//设置图片
					info.setImg(status.getOriginalPic());
					//设置添加用户
					info.setAdduser(userInfo.getUsername());
					//设置微博ID
					info.setWeiboid(status.getId());
					infoService.saveInfo(info);
					result = SUCCESS;
				}
			} catch (WeiboException e) {
				logger.error(WeiboCons.getErrorMsg(e));
				result = ERROR_WEIBO;
				errorWeiboMsg.append("调用微博接口出现异常[").append(WeiboCons.getErrorMsg(e)).append("]!");
			} catch (Exception e) {
				result = ERROR;
				logger.error(userInfo.getNickname() + ": 添加信息异常!", e);
			}
		}
		modelMap.put("result", result);
		modelMap.put("errorWeiboMsg", errorWeiboMsg.toString());
		return modelMap;
	}

	/**
	 * 转发信息
	 * @return
	 */
	@RequestMapping(value = "/info/json/transpondInfo")
	@ResponseBody
	public ModelMap transpondInfo(HttpServletRequest request, Info info, String transpondContent) {
		String result = null;
		StringBuffer errorWeiboMsg = new StringBuffer();
		UserInfo userInfo = getSessionUser(request);
		if(userInfo == null) {
			result = ERROR_NOT_LOGIN;
		}
		else {
			try {
				info = infoService.findByIdInfo(info.getId());
				//转发信息到微博
				timelineService.repost(info.getWeiboid(), transpondContent + SystemCons.getInfoTranspondContent(info.getTranspondnum(), info.getId()), 1, userInfo.getToken());
				//根据ID修改信息转发数
				info.setTranspondnum(info.getTranspondnum() + 1);
				infoService.updateInfoTranspond(info);
				result = SUCCESS;
			} catch (WeiboException e) {
				logger.error(WeiboCons.getErrorMsg(e));
				result = ERROR_WEIBO;
				errorWeiboMsg.append("调用微博接口出现异常[").append(WeiboCons.getErrorMsg(e)).append("]!");
			} catch (Exception e) {
				result = ERROR;
				logger.error(userInfo.getNickname() + ": 转发信息异常!", e);
			}
		}
		ModelMap modelMap = new ModelMap();
		modelMap.put("result", result);
		modelMap.put("errorWeiboMsg", errorWeiboMsg.toString());
		return modelMap;
	}

	/**
	 * 跳转到信息管理页面
	 * @param request
	 * @return
	 */
	@RequestMapping("/toInfoManager")
	public String toInfoManager(HttpServletRequest request, ModelMap modelMap) {
		UserInfo userInfo = getSessionUser(request);
		//不为管理员
		if(userInfo.getIsadmin().intValue() != 1) {
			logger.error(userInfo.getNickname() + ": 您不是管理员!");
			return ERROR_ADMIN;
		}

		try {
			//获取信息类型
			List<InfoType> infoTypeList = infoTypeService.findAllInfoType();
			modelMap.put("infoTypeList", infoTypeList);
		} catch (Exception e) {
			logger.error("获取信息类型异常!", e);
		}
		return "admin/info/info_manager";
	}

	/**
	 * 获取浏览信息列表
	 * @return
	 */
	@RequestMapping(value = "/p/findInfo")
	@ResponseBody
	public ModelMap findInfo(HttpServletRequest request, Info info) {
		String result = null;
		String weiboMsg = null;
		Map<String, Object> map = null;
		UserInfo userInfo = getSessionUser(request);
		try {
			map = infoService.findInfo(info);
			result = SUCCESS;
		} catch (Exception e) {
			logger.error(userInfo.getNickname() + ": 获取获取浏览信息列表异常!", e);
			result = ERROR;
		}
		ModelMap modelMap = new ModelMap();
		modelMap.put("data", map);
		modelMap.put("result", result);
		modelMap.put("weiboMsg", weiboMsg);
		return modelMap;
	}

}